package com.csxy.chy.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csxy.chy.R;
import com.csxy.chy.entity.vo.EduComment;
import com.csxy.chy.exception.MyException;
import com.csxy.chy.service.EduCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/eduservice/edu-comment")
public class EduCommentController {
    @Autowired
    private EduCommentService eduCommentService;
    @GetMapping("getCommentPage/{page}/{limit}")
    public R getCommentPage(@PathVariable long page, @PathVariable long limit, String courseId){
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        Page<EduComment> pageComment = new Page<>(page,limit);
        
        // 只有当courseId不为空时才添加查询条件
        if (!StringUtils.isEmpty(courseId)){
            wrapper.eq("course_id",courseId);
        }
        wrapper.orderByDesc("gmt_create");

        //数据会被封装到commentPage中
        eduCommentService.page(pageComment,wrapper);

        List<EduComment> commentList = pageComment.getRecords();
        long current = pageComment.getCurrent();//当前页
        long size = pageComment.getSize();//一页记录数
        long total = pageComment.getTotal();//总记录数
        long pages = pageComment.getPages();//总页数
        boolean hasPrevious = pageComment.hasPrevious(); //是否有上页
        boolean hasNext = pageComment.hasNext(); //是否有下页
        HashMap<String, Object> map = new HashMap<>();
        map.put("current", current);
        map.put("size", size);
        map.put("total", total);
        map.put("pages", pages);
        map.put("hasPrevious", hasPrevious);
        map.put("hasNext", hasNext);
        map.put("list", commentList);
        return R.ok().data(map);

    }

    @PostMapping("/auth/addComment")
    public R addComment(@RequestBody EduComment comment) {
        eduCommentService.save(comment);
        return R.ok();
    }
}
